package com.wxxymakers.grademark.controller;

import com.wxxymakers.grademark.model.entity.WxDepartment;
import com.wxxymakers.grademark.service.WxDepartmentService;
import com.wxxymakers.grademark.utils.RestResponse;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @AUTHOR soft
 * @DATE 2018/12/23 19:28
 * @DESCRIBE 部门控制器
 */
@RestController
@RequestMapping("/dept")
public class DepartmentController {

    @Autowired
    private WxDepartmentService departmentService;

    @RequiresRoles(value = {"admin"})
    @PostMapping("/add")
    public RestResponse add(WxDepartment department) {
        if (departmentService.add(department)) {
            return RestResponse.ok(department);
        }
        return RestResponse.fail("添加失败！");
    }

    @PostMapping("/delete/{id}")
    @RequiresRoles({"admin"})
    public RestResponse delete(@PathVariable int id) {
        if (departmentService.delete(id)) {
            return RestResponse.ok();
        }
        return RestResponse.fail();
    }

    @PostMapping("/change")
    @RequiresRoles({"admin"})
    public RestResponse change(WxDepartment department) {
        if (departmentService.change(department)) {
            return RestResponse.ok();
        }
        return RestResponse.fail();
    }

    @PostMapping("/get/{id}")
    public RestResponse get(@PathVariable int id) {
        WxDepartment wxDepartment = departmentService.byId(id);
        if (wxDepartment != null) {
            return RestResponse.ok(wxDepartment);
        }
        return RestResponse.fail();
    }

    /**
     * 根据学院id 获取所有部门 不需要权限
     * 如果学院id不存在 或者id小于等于0 则查询全部
     */
    @PostMapping("/list")
    public RestResponse list(@RequestParam("cgid") Integer collageId) {
        List<WxDepartment> list = departmentService.list(collageId);
        if (!CollectionUtils.isEmpty(list)) {
            return RestResponse.ok(list);
        }
        return RestResponse.fail();
    }

    @PostMapping("/page")
    public RestResponse page(@RequestParam int page,
                             @RequestParam int limit,
                             WxDepartment department) {
        Page<WxDepartment> departments = departmentService.page(page, limit, department);
        if (departments != null) {
            return RestResponse.ok(departments);
        }
        return RestResponse.fail();
    }
}
